//
//  YMTravelTrackViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/11/9.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "YMTravelTrackViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <Masonry.h>
#import <ReactiveObjC.h>
#import <YYKit.h>
#import "YMTravelTrack.h"
#import "YMStationAnnotation.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "MANaviRoute.h"
#import "SYDTravelTrackBottonView.h"

@interface YMTravelTrackViewController ()<MAMapViewDelegate, AMapSearchDelegate>
@property(nonatomic, strong) MAMapView *mapView;
@property(nonatomic, strong) MAAnimatedAnnotation* annotation;
@property(nonatomic, assign) CLLocationCoordinate2D * coordinates;
@property(nonatomic, strong) NSArray *lines;
@property(nonatomic, assign) BOOL showStationInfo;
@property(nonatomic, assign) CGFloat preLevel;
@property(nonatomic, strong) NSMutableArray * makers;
@property(nonatomic, strong) AMapSearchAPI *search;
/* 用于显示当前路线方案. */
@property(nonatomic) MANaviRoute * naviRoute;
@property(nonatomic, strong) AMapRoute *route;
@property(nonatomic, strong) YMStationAnnotation *firstAnno;
@property(nonatomic, strong) YMStationAnnotation *lastAnno;
@property(nonatomic, strong) SYDTravelTrackBottonView *bottomView;
@property(nonatomic, assign) BOOL turn;

@end

@implementation YMTravelTrackViewController
- (NSMutableArray *)makers{
    if (!_makers) {
        _makers = [NSMutableArray array];
    }
    return _makers;
}

- (SYDTravelTrackBottonView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[SYDTravelTrackBottonView alloc] initWithFrame:CGRectMake(0, self.view.height - 85, self.view.width, 205)];
        [self.view addSubview:_bottomView];
    }
    return _bottomView;
}

- (MAMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
        _mapView.zoomLevel = 16.1;
        _mapView.delegate = self;
        [self.view addSubview:_mapView];
        
        [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.navigationBar.height);
            make.left.equalTo(@0);
            make.right.equalTo(@0);
            make.bottom.equalTo(@0);
        }];
    }
    return _mapView;
}

- (AMapSearchAPI *)search{
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}

- (void)readData{
    NSString * path = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"traveltrack.json"];
    NSData * data = [NSData dataWithContentsOfFile:path];
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    if (dic) {
        [YMAutoGenerateModelTool propertyWithDictionary:dic];
        //        YMTravelTrack * travelTrack = [YMTravelTrack mj_objectWithKeyValues:dic[@"obj"]];
        YMTravelTrack * travelTrack = [YMTravelTrack modelWithDictionary:dic[@"obj"]];
//        NSLog(@"%@", travelTrack.firstStationName);
        self.lines = [travelTrack.trailDetail componentsSeparatedByString:@"|"];
        [self drawLinePath:self.lines];
        [self addMarkers:travelTrack.carpoolRouteStations];
    }
}

// add station marker
- (void)addMarkers:(NSArray *)stations{
    
    if (self.makers.count > 0) {
        [self.mapView addAnnotations:self.makers];
        return;
    }
    
    stations = [stations sortedArrayUsingComparator:^NSComparisonResult(YMStation  * obj1, YMStation * obj2) {
        if ([obj1.stationNo integerValue] < [obj1.stationNo integerValue]) {
            return NSOrderedAscending;
        }
        return NSOrderedDescending;
    }];
    
    for (YMStation * sta in stations) {
        YMStationAnnotation * anno = [[YMStationAnnotation alloc] init];
        anno.coordinate = CLLocationCoordinate2DMake([sta.stationLat doubleValue], [sta.stationLon doubleValue]);
        anno.station = sta;
        [self.makers addObject:anno];
    }
    [self.mapView addAnnotations:self.makers];
    
    NSArray *routes = [self spilitArray:self.makers size:15];
    
    for (NSArray * array in routes) {
        [self drivePlan:array];
    }
}

- (NSArray *)spilitArray:(NSArray *)array size:(NSInteger)subSize{
    
    NSInteger count = array.count % subSize == 0 ? array.count / subSize : array.count / subSize + 1;
    
    NSMutableArray * subArray = [NSMutableArray array];
    
    for (NSInteger i = 0; i < count; i++) {
        
        NSInteger index = i * subSize;
        
        NSMutableArray * list = [NSMutableArray array];
        
        NSInteger j = 0;
        while (j < subSize && index < array.count) {
            [list addObject:array[index++]];
            j++;
        }
        if (index < array.count) {
            [list addObject:array[index + 1]];
        }
        [subArray addObject:list];
    }
    return subArray;
}

- (void)drivePlan:(NSArray *)makers{
    
    NSMutableArray * points = [NSMutableArray array];
    for (YMStationAnnotation * anno in makers) {
        AMapGeoPoint * point = [AMapGeoPoint locationWithLatitude:anno.coordinate.latitude longitude:anno.coordinate.longitude];
        [points addObject:point];
    }
    
    for (NSInteger i = 0; i < makers.count; i++) {
        if (i != self.makers.count - 1) {
            self.firstAnno = makers.firstObject;
            self.lastAnno = makers.lastObject;
            
            AMapDrivingRouteSearchRequest * navi = [[AMapDrivingRouteSearchRequest alloc] init];
            navi.requireExtension = YES;
            navi.origin = [AMapGeoPoint locationWithLatitude:self.firstAnno.coordinate.latitude longitude:self.firstAnno.coordinate.longitude];
            navi.destination = [AMapGeoPoint locationWithLatitude:self.lastAnno.coordinate.latitude longitude:self.lastAnno.coordinate.longitude];
            navi.waypoints = points;
            [self.search AMapDrivingRouteSearch:navi];
            
            if (i == self.makers.count / 2) {
                YMStationAnnotation * anno = self.makers[self.makers.count / 2];
                [self.mapView setCenterCoordinate:anno.coordinate];
            }
        }
    }
}

// draw line on map
- (void)drawLinePath:(NSArray *)lines{
    CLLocationCoordinate2D linePoints[lines.count];
    NSArray * locs = [self generateLocations];
    for (int i = 0; i < locs.count ; i++) {
        CLLocation * loc = locs[i];
        linePoints[i] = loc.coordinate;
        
        if (i == 0) {
            [self.mapView setCenterCoordinate:loc.coordinate];
            
            MAAnimatedAnnotation * anno = [[MAAnimatedAnnotation alloc] init];
            anno.coordinate = loc.coordinate;
            self.annotation = anno;
        }
    }
    
    //    MAPolyline * polyline = [MAPolyline polylineWithCoordinates:linePoints count:locs.count];
    //    [self.mapView addOverlay:polyline];
    [self.mapView addAnnotation:self.annotation];
}

- (NSMutableArray *)generateLocations{
    NSMutableArray * locaitons = [NSMutableArray array];
    for (int i = 0; i < self.lines.count; i++) {
        NSString * temp = self.lines[i];
        NSArray * points = [temp componentsSeparatedByString:@","];
        CLLocation * loc = [[CLLocation alloc] initWithLatitude:[points[1] doubleValue] longitude:[points[0] doubleValue]];
        [locaitons addObject:loc];
    }
    
    return locaitons;
}

- (void)go:(CLLocationCoordinate2D *)coordinates count:(NSInteger)count completaCallback:(void(^)(BOOL isFinished))completaCallback {
    [self.annotation addMoveAnimationWithKeyCoordinates:coordinates count:count withDuration:10 withName:nil completeCallback:^(BOOL isFinished) {
        completaCallback(isFinished);
    }];
}

#pragma mark - 导航栏
- (void)navigationBarHandle{
    self.navigationBar.title = @"行程轨迹";
    WEAKSELF
    [self leftNavButtonWithImage:[UIImage imageNamed:@"nav_button_return"] action:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self navigationBarHandle];
//    [self readData];
    
    NSLog(@"--->%@",self.orderNo);
    [self getTravelTrack];
    
    WEAKSELF    
    [self.bottomView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        weakSelf.turn = !weakSelf.turn;
        [weakSelf.bottomView.turnBtn setImage:[UIImage imageNamed:weakSelf.turn ? @"button_close" : @"button_open"] forState:UIControlStateNormal];
        
        if (weakSelf.turn) {
            self.bottomView.y = self.view.height - 205;
        }else{
            self.bottomView.y = self.view.height - 85;
        }
    }];
}

- (void)getTravelTrack{
    WEAKSELF
    [[SYDNetwork shareTool] getMyTrailDetailWithOrderNo:self.orderNo success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"--->%@",[responseObject mj_JSONString]);
        
        @try{
            if (responseObject[@"success"]) {
                YMTravelTrack * travelTrack = [YMTravelTrack modelWithDictionary:responseObject[@"obj"]];
                weakSelf.bottomView.model = travelTrack;
                weakSelf.lines = [travelTrack.trailDetail componentsSeparatedByString:@"|"];
                [weakSelf drawLinePath:weakSelf.lines];
                [weakSelf addMarkers:travelTrack.carpoolRouteStations];
            }else{
                
            }
        }
        @catch(NSException * e){
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)presentCurrentCourse{
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths.lastObject
                                      withNaviType:type
                                       showTraffic:YES
                                        startPoint:[AMapGeoPoint locationWithLatitude:self.firstAnno.coordinate.latitude longitude:self.firstAnno.coordinate.longitude]
                                          endPoint:[AMapGeoPoint locationWithLatitude:self.lastAnno.coordinate.latitude longitude:self.lastAnno.coordinate.longitude]
                      ];
    [self.naviRoute addToMapView:self.mapView];
}

#pragma mark - MAMapViewDelegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[YMStationAnnotation class]]){ // station
        if (_showStationInfo) {
            NSString *reuseIndetifier = @"staInfoReuseIndetifier";
            YMStationAnnotationView * annotationView = (YMStationAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
            if (annotationView == nil) {
                annotationView = [[YMStationAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
            }
            YMStationAnnotation * anno = (YMStationAnnotation *)annotation;
            annotationView.station = anno.station;
            return annotationView;
        }else{
            NSString *reuseIndetifier = @"staReuseIndetifier";
            YMStationAnnotationIconView * annotationView = (YMStationAnnotationIconView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
            if (annotationView == nil) {
                annotationView = [[YMStationAnnotationIconView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
            }
            return annotationView;
        }
    }else if ([annotation isKindOfClass:[MAPointAnnotation class]]) { // car
        NSString *reuseIndetifier = @"myReuseIndetifier";
        MAAnnotationView * annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
            UIImage * image = [UIImage imageNamed:@"icon_car"];
            annotationView.image = image;
        }
        return annotationView;
    }
    return nil;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
        polylineRenderer.lineWidth    = 5.f;
        [polylineRenderer loadStrokeTextureImage:[UIImage imageNamed:@"arrowTexture"]];
        return polylineRenderer;
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    NSLog(@"--level-%f", mapView.zoomLevel);
    if (_preLevel == mapView.zoomLevel) {
        return;
    }
    
    if (mapView.zoomLevel > 16) {
        _preLevel = mapView.zoomLevel;
        _showStationInfo = YES;
    }else{
        _showStationInfo = NO;
    }
    
    [mapView removeAnnotations:self.makers];
    [self addMarkers:self.makers];
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"%@",error.localizedDescription);
}

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    NSLog(@"%@",response);
    self.route = response.route;
    [self presentCurrentCourse];
    
}

@end
